//
//  CountDown.m
//  xinLing
//
//  Created by 于鹏 on 2017/7/27.
//  Copyright © 2017年 YIVIEW. All rights reserved.
//

#import "CountDown.h"

@interface CountDown ()

@property (nonatomic, retain)dispatch_source_t timer;

@end

@implementation CountDown

- (void)countDownWithTime:(NSInteger)totalTime completeBlock:(void (^)(NSInteger))completeBlock {
    __block NSInteger timeout=totalTime; //倒计时时间
    //全局队列 默认优先级
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式 事件源
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //NSEC_PER_SEC是秒 *1每一秒执行一次
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //设置响应dispath源事件的block,在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(_timer, ^{
        //回调主线程,在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (timeout <= 0) {
                //倒计时结束,关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    completeBlock(0);
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completeBlock(timeout);
                });
                timeout--;
            }
        });
    });
    dispatch_resume(_timer);
}

- (void)destoryTimer {
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

@end
